package com.winit.openapi.wh.builder;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.util.StringUtils;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.winit.oms.spi.inbound.command.CreateOrUpdateDirectForcenoticeCommand;
import com.winit.oms.spi.inbound.vo.DirectInnerInboundOrderVo;
import com.winit.oms.spi.inbound.vo.DirectWhInboundOrderVo;
import com.winit.oms.spi.inbound.vo.InboundCustomsDataFileVo;
import com.winit.oms.spi.inbound.vo.InboundDispatchinfoVo;
import com.winit.oms.spi.inbound.vo.InboundEnumConstant;
import com.winit.oms.spi.inbound.vo.InboundMerchandiseDetailsVo;
import com.winit.oms.spi.inbound.vo.InboundOrderTrackingVo;
import com.winit.oms.spi.inbound.vo.InboundOrderVo;
import com.winit.oms.spi.inbound.vo.InboundPackageVo;
import com.winit.oms.spi.inbound.vo.StandardInboundOrderVo;
import com.winit.oms.spi.inbound.vo.StorageWhInboundOrderVo;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.util.DateUtil;

/**
 * 海外仓入库单构造器
 * 
 * @version <pre>
 * Author     Version       Date        Changes
 * dinghua.an   1.0         2015年11月10日     Created
 *
 * </pre>
 * @since 1.
 */
public class InboundOrderBuilder {

    /**
     * 构建订单列表页面的行值
     * 
     * @param json
     * @return
     */
    public static Map<String, Object> buildInboundOrderListPageVo(InboundOrderVo inboundOrder) {
        Map<String, Object> map = new HashMap<String, Object>();
        
        map.put("slaCalType", inboundOrder.getSlaCalType());
        map.put("isOnTime", inboundOrder.getIsOnTime());
        map.put("serviceStatus", inboundOrder.getServiceStatus());
        map.put("serviceStandardTime", inboundOrder.getServiceStandardTime());
        map.put("serviceCompleteTime", inboundOrder.getServiceCompleteTime());
        map.put("entryWhType", inboundOrder.getEntryWhType());
        map.put("orderNo", inboundOrder.getOrderNo());
        map.put("needReservationSendWh", inboundOrder.getNeedReservationSendWh());
        map.put("destWhCode", inboundOrder.getDestWhCode());
        map.put("destWhName", inboundOrder.getDestWhName());
        map.put("winitProductCode", inboundOrder.getWinitProductCode());
        map.put("winitProductName", inboundOrder.getWinitProductName());
        map.put("shelveCompletedDate", inboundOrder.getShelveCompletedDate());
        map.put("isFinance", inboundOrder.getIsFinance());
        map.put("dispatchPrintable", inboundOrder.getDispatchPrintable());
        
        map.put("mergeType", inboundOrder.getMergeType());
        map.put("mainOrderNo", inboundOrder.getMainOrderNo());
        map.put("transportType", inboundOrder.getTransprotType());
        map.put("inspectionType", inboundOrder.getInspectionType());
        
        map.put("pickupType", inboundOrder.getPickupType());
        map.put("inspectionWhName", inboundOrder.getInspectionWhName());
        String pickupCompletedDate = DateUtil.parse2String(inboundOrder.getPickupCompletedDate(),
            DateUtil.FULL_DATE_STRING);
        map.put("pickupCompletedDate", pickupCompletedDate);

        map.put("packageQty",
            (inboundOrder.getOrderPackageQty() == null ? 0 : inboundOrder.getOrderPackageQty()) + "|"
                    + (inboundOrder.getActualOrderPackageQty() == null ? 0 : inboundOrder.getActualOrderPackageQty()));

        map.put("itemQty", (inboundOrder.getOrderItemQty() == null ? 0 : inboundOrder.getOrderItemQty()) + "|"
                           + (inboundOrder.getActualOrderItemQty() == null ? 0 : inboundOrder.getActualOrderItemQty()));

        map.put("merchandiseQty", (inboundOrder.getOrderMerchandiseQty() == null ? 0 : inboundOrder.getOrderMerchandiseQty()) + "|"
                + (inboundOrder.getActualOrderMerchandiseQty() == null ? 0 : inboundOrder.getActualOrderMerchandiseQty()));
        
        BigDecimal weight = inboundOrder.getOrderWeight();
        if (weight == null || BigDecimal.ZERO.compareTo(weight) >= 0) {
            weight = BigDecimal.ZERO;
        }
        BigDecimal acthalWeight = inboundOrder.getActualOrderWeight();
        if (acthalWeight == null || BigDecimal.ZERO.compareTo(acthalWeight) >= 0) {
            acthalWeight = BigDecimal.ZERO;
        }
        map.put("weight", weight + "|" + acthalWeight);

        BigDecimal volumn = inboundOrder.getOrderVolume();
        if (volumn == null || BigDecimal.ZERO.compareTo(volumn) >= 0) {
            volumn = BigDecimal.ZERO;
        }
        BigDecimal acthalVolumn = inboundOrder.getActualOrderVolume();
        if (acthalVolumn == null || BigDecimal.ZERO.compareTo(acthalVolumn) >= 0) {
            acthalVolumn = BigDecimal.ZERO;
        }
        map.put("volumn", volumn + "|" + acthalVolumn);

        String orderDate = DateUtil.parse2String(inboundOrder.getOrderDate(), DateUtil.FULL_DATE_STRING);
        map.put("orderDate", orderDate);
        String voidDate = DateUtil.parse2String(inboundOrder.getVoidDate(), DateUtil.FULL_DATE_STRING);
        map.put("voidDate", voidDate);

        map.put("status", inboundOrder.getStatus());
        map.put("reservationOrderNo", inboundOrder.getReservationOrderNo());
        map.put("takeEffectDate", inboundOrder.getTakeEffectDate());
        InboundEnumConstant.OrderStatus status = InboundEnumConstant.OrderStatus.valueOf(inboundOrder.getStatus());
        if (status != null) {
            map.put("statusDesc", status.getDesc());
        } else {
            map.put("statusDesc", "undefined");
        }
        
        //是否支持越库
        map.put("isSupportCrossDock", inboundOrder.getIsSupportCrossDock());
        if ("Y".equals(inboundOrder.getIsSupportCrossDock())) {
            map.put("isCrossDockEnd", inboundOrder.getIsCrossDockEnd());
            map.put("allocationOrderNo", inboundOrder.getAllocationOrderNo());
        }
        map.put("expectedSendWarehouseTime", inboundOrder.getExpectedSendwarehouseTime());
        map.put("expectedSendWarehouseWay", inboundOrder.getExpectedSendWarehouseWay());
        map.put("onwardVoyageType", inboundOrder.getOnwardVoyageType());
        map.put("isBookingAllowed",isBookingAllowed(inboundOrder));//是否允许预约
        return map;
    }
    
    
    /**
     *  是否允许预约
     * @param inboundOrder
     * @return
     */
    private static String isBookingAllowed(InboundOrderVo inboundOrder) {
    	if(!StringUtils.isEmpty(inboundOrder.getBookingNo())){
    		return "N";
    	}else{
    		if(!InboundEnumConstant.OnwardVoyageType.Direct.getType().equals(inboundOrder.getOnwardVoyageType())){
    			return "N";
    		}else{
    			if(InboundEnumConstant.OrderType.DIRECT_WH.getType().equals(inboundOrder.getEntryWhType())){
    				if(InboundEnumConstant.OrderStatus.DR.getStatus().equals(inboundOrder.getStatus())
    						|| InboundEnumConstant.OrderStatus.SHD.getStatus().equals(inboundOrder.getStatus()) 
    						|| InboundEnumConstant.OrderStatus.VO.getStatus().equals(inboundOrder.getStatus())
    						|| InboundEnumConstant.OrderStatus.STOP.getStatus().equals(inboundOrder.getStatus())){
    					return "N";
    				}else{
    					return "Y";
    				}
    			}else{
    				if(InboundEnumConstant.OrderStatus.DR.getStatus().equals(inboundOrder.getStatus())
    						|| InboundEnumConstant.OrderStatus.SHD.getStatus().equals(inboundOrder.getStatus()) 
    						|| InboundEnumConstant.OrderStatus.VO.getStatus().equals(inboundOrder.getStatus())
    						|| InboundEnumConstant.OrderStatus.STOP.getStatus().equals(inboundOrder.getStatus())){
    					return "N";
    				}else{
    					if(null != inboundOrder.getActualOrderItemQty() && inboundOrder.getActualOrderItemQty() > 0){
    						return "Y";
    					}else{
    						return "N";
    					}
    				}
    			}
    		}
    	}
	}


	/**
     * 构建保存到草稿入库参数
     * 
     * @param json
     * @return
     */
    public static InboundOrderVo buildInboundOrder(JSONObject json) {
        String orderType = json.getString("orderType").trim();
        if (InboundEnumConstant.OrderType.STANDARD.getType().equals(orderType)) {
            StandardInboundOrderVo vo = new StandardInboundOrderVo();
            buildCommon(vo, json);
            if (json.containsKey("isFinance")) {
                vo.setIsFinance(json.getString("isFinance").trim());
                if ("Y".equals(json.getString("isFinance"))) {
                    // 贷款单号
                    if (json.containsKey("loanNo")) {
                        vo.setLoanNo(json.getString("loanNo").trim());
                    }
                }
            }
            return vo;
        } else if (InboundEnumConstant.OrderType.DIRECT_INNER.getType().equals(orderType)) {
            DirectInnerInboundOrderVo vo = new DirectInnerInboundOrderVo();
            if (json.containsKey("transportType")) {
                vo.setTransprotType(json.getString("transportType"));
            } 
            buildCommon(vo, json);
            return vo;
        } else if (InboundEnumConstant.OrderType.DIRECT_WH.getType().equals(orderType)) {
            DirectWhInboundOrderVo vo = new DirectWhInboundOrderVo();
            if (json.containsKey("transportType")) {
                vo.setTransprotType(json.getString("transportType"));
            } 
            buildCommon(vo, json);
            //直发海外验目的仓和验货仓一致
            if(StringUtils.isEmpty(vo.getInspectionWhCode())){
            	vo.setInspectionWhCode(vo.getDestWhCode());
            }
            return vo;
        } else if (InboundEnumConstant.OrderType.LOCATION_INBOUND.getType().equals(orderType)) {
            DirectWhInboundOrderVo vo = new DirectWhInboundOrderVo();
            buildCommon(vo, json);
            return vo;
        }else if (InboundEnumConstant.OrderType.STORAGE_INBOUND.getType().equals(orderType)) {
            StorageWhInboundOrderVo vo = new StorageWhInboundOrderVo();
            buildCommon(vo, json);
            return vo;
        } else if (InboundEnumConstant.OrderType.STORAGE_DIRECT_INNER.getType().equals(orderType)) {
            StorageWhInboundOrderVo vo = new StorageWhInboundOrderVo();
            buildCommon(vo, json);
            return vo;
        }
        else {
            throw new ApiException("不支持的订单类型不支持!");
        }
    }

    public static CreateOrUpdateDirectForcenoticeCommand buildDirectForenotice(JSONObject json) {
        CreateOrUpdateDirectForcenoticeCommand command = new CreateOrUpdateDirectForcenoticeCommand();
        command.setOrderNo(json.getString("orderNo").trim());
        String orderDateStart = json.getString("preparedOffPortDate");
        orderDateStart += " 00:00:00";
        Date preparedOffPortDate = DateUtil.parse2Date(orderDateStart, DateUtil.FULL_DATE_STRING);
        command.setPreparedOffPortDate(preparedOffPortDate);
        String orderDateEnd = json.getString("preparedArrivePortDate");
        orderDateEnd += " 00:00:00";
        command.setForecastWarehouseTime(orderDateEnd);
        Date preparedArrivePortDate = DateUtil.parse2Date(orderDateEnd, DateUtil.FULL_DATE_STRING);
        command.setPreparedArrivePortDate(preparedArrivePortDate);
        command.setTransportType(json.getString("transportType"));
        command.setTransportAgent(json.getString("transportAgent"));
        command.setPickUpNo(json.getString("pickUpNo"));
        command.setSendWarehouseContactName(json.getString("sendWarehouseContactName"));
        command.setSendWarehouseContactNumber(json.getString("sendWarehouseContactNumber"));
        command.setContainerNo(json.getString("containerNo"));
        command.setSealNo(json.getString("sealNo").trim());
        return command;
    }
    
    /**
     * 更新vo的方式build提货信息
     * 
     * @param json
     * @param vo
     */
    public static void buildUnpickupInboundOrder(JSONObject json, InboundOrderVo vo) {
        buildLogisticInfo(json, vo);
    }

    /**
     * 新建vo的方式build提货信息
     * 
     * @param json
     * @param vo
     */
    public static InboundOrderVo buildUnpickupInboundOrder(JSONObject json) {
        String entryWhType = (String) json.get("entryWhType");
        InboundOrderVo result = new InboundOrderVo();
        result.setEntryWhType(entryWhType);
        buildLogisticInfo(json, result);
        return result;
    }

    /**
     * 组装查询订单详情返回参数
     * 
     * @param order
     * @param orderType
     * @return
     */
    public static Map<String, Object> buildReturnInboundOrderInfo(InboundOrderVo order) {
        Map<String, Object> map = new HashMap<String, Object>();
        /************************** 基本信息 ***********************/
        map.put("orderNo", order.getOrderNo());
        map.put("needReservationSendWh", order.getNeedReservationSendWh());
        map.put("customerOrderNo", order.getCustomerOrderNo());
        map.put("warehouseCode", order.getInspectionWhCode());
        map.put("warehouseName", order.getInspectionWhName());
        map.put("destWhCode", order.getDestWhCode());
        map.put("destWhName", order.getDestWhName());
        map.put("winitProductCode", order.getWinitProductCode());
        map.put("winitProductName", order.getWinitProductName());
        map.put("desc", order.getDesc());
        map.put("status", order.getStatus());
        map.put("createdDate", (DateUtil.parse2String(order.getCreated(), DateUtil.FULL_DATE_STRING)));
        map.put("logisticsPlanNo", order.getLogisticsPlanId());
        map.put("logisticsPlanName", order.getLogisticsPlanName());
        map.put("importerCode", order.getImporterId());
        map.put("importerName", order.getImporterName());
        map.put("exporterCode", order.getExporterId());
        map.put("exporterName", order.getExporterName());
        map.put("importDeclarationRuleCode", order.getImportDeclarationRuleCode());
        map.put("importDeclarationRuleName", order.getImportDeclarationRuleName());
        map.put("importDeclareWay", order.getImportDeclareWay());
        map.put("importDeclareValue", order.getImportDeclareValueType());
        map.put("importDeclarationType", order.getImportDeclarationType());
        map.put("importDeclarationName", order.getImportDeclarationName());
        map.put("customsDeclarationType", order.getCustomsDeclarationType());
        map.put("customsDeclarationName", order.getCustomsDeclarationName());
        map.put("orderPackageQty", order.getOrderPackageQty());
        map.put("orderMerchandiseQty", order.getOrderMerchandiseQty());
        map.put("orderItemQty", order.getOrderItemQty());
        map.put("actualOrderPackageQty", order.getActualOrderPackageQty());
        map.put("actualOrderMerchandiseQty", order.getActualOrderMerchandiseQty());
        map.put("actualOrderItemQty", order.getActualOrderItemQty());
        map.put("takeEffectDate", order.getTakeEffectDate());
        map.put("isFinance", order.getIsFinance());
        map.put("loanNo", order.getLoanNo());
        map.put("customsData", order.getCustomsData());
        map.put("estimateShelveCompletedDate", order.getEstimateShelveCompletedDate()); //目标上架时间（与名称反过来了）
        map.put("goalShelveDate", order.getGoalShelveDate()); //预计上架时间（与名称反过来了）
        map.put("isShowEstimateShelveTime", order.getIsShowEstimateShelveTime());
        map.put("entryWhType", order.getEntryWhType());
        map.put("orderDate", order.getOrderDate());
        map.put("exportDeclarationType", order.getCustomsDeclarationType());
        /************************* 验货提货 ************************/
        if (order.getInboundDispatchinfoVo() == null) {
            order.setInboundDispatchinfoVo(new InboundDispatchinfoVo());
        }
        map.put("inspectionType", order.getInboundDispatchinfoVo().getInspectionType());
        map.put("pickupType", order.getInboundDispatchinfoVo().getPickupType());
        map.put("dateExpectFrom", order.getInboundDispatchinfoVo().getExpectFromDate());
        map.put("dateExpectTo", order.getInboundDispatchinfoVo().getExpectToDate());
        map.put("addressCode", order.getInboundDispatchinfoVo().getAddressCode());
        map.put("address", order.getInboundDispatchinfoVo().getAddress());
        map.put("expressVendorCode", order.getInboundDispatchinfoVo().getExpressVendorCode());
        map.put("expressVendorName", order.getInboundDispatchinfoVo().getExpressVendorName());
        map.put("expressNo", order.getInboundDispatchinfoVo().getExpressNo());
        map.put("dispatchPrintable", order.getInboundDispatchinfoVo().getDispatchPrintable());
        buildDateAndTime(map, order.getInboundDispatchinfoVo().getExpectFromDate(), order.getInboundDispatchinfoVo()
            .getExpectToDate());

        /************************* 直发信息 ************************/
        map.put("transportType", order.getTransprotType());
        map.put("transportAgent", order.getTransportAgent());
        map.put("pickUpNo", order.getPickUpNo());
        map.put("sendWarehouseContactName", order.getSendWarehouseContactName());
        map.put("sendWarehouseContactNumber", order.getSendWarehouseContactNumber());
        map.put("sealNo", order.getSealNo());
        if(order.getPreparedOffPortDate() != null && order.getPreparedArrivePortDate() != null){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String offPortDate = dateFormat.format(order.getPreparedOffPortDate());
            String arrivePortDate = dateFormat.format(order.getPreparedArrivePortDate());
            map.put("preparedOffPortDate", offPortDate);
            map.put("preparedArrivePortDate",(arrivePortDate));
        }
        map.put("expectedSendWarehouseTime", order.getExpectedSendwarehouseTime());
        map.put("expectedSendWarehouseWay", order.getExpectedSendWarehouseWay());
        map.put("containerNo", order.getContainerNo());
        map.put("sealNo", order.getSealNo());
        /************************* 送港信息 ************************/
        map.put("isSelfInspection", order.getIsSelfInspection());
        map.put("onwardVoyageType", order.getOnwardVoyageType());
        map.put("sendPortDate", order.getSendPortDate());
        map.put("sendPortType", order.getSendPortType());
        map.put("pickupCartonAddrCode", order.getPickupCartonAddrCode());
        map.put("pickupCartonAddrName", order.getPickupCartonAddrName());
       // buildPickupCartonDateAndTime(map, order.getPickupCartonFromDate(), order.getPickupCartonToDate());
        // 构建进出口报关资料
        List<Map<String, Object>> exportFileList = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> importFileList = new ArrayList<Map<String, Object>>();
        Map<String, Object> customsDataFileVos = null;
        if (CollectionUtils.isNotEmpty(order.getCustomsDataFileVos())) {
            for (InboundCustomsDataFileVo vo : order.getCustomsDataFileVos()) {
                customsDataFileVos = InboundCustomsDataFileBuilder.buildInboundCustomsDataFileMap(vo);

                if ("export".equals(vo.getCustomsDataType())) {
                    exportFileList.add(customsDataFileVos);
                } else {
                    importFileList.add(customsDataFileVos);
                }

            }
        }
        map.put("exportFileList", exportFileList);
        map.put("importFileList", importFileList);
        map.put("inspectionStatus", order.getInspectionStatus());
        return map;

    }
    
    /**
     * 组装查询订单详情返回参数
     * 
     * @param order
     * @param orderType
     * @return
     */
    public static Map<String, Object> buildReturnInboundOrderInfoForAPI(InboundOrderVo order,boolean isIncludePackage) {
        Map<String, Object> map = new HashMap<String, Object>();
        /************************** 基本信息 ***********************/
        map.put("orderNo", order.getOrderNo());
        map.put("orderType", order.getEntryWhType());
        map.put("status", order.getStatus());
        map.put("needReservationSendWh", order.getNeedReservationSendWh());
        map.put("sellerOrderNo", order.getCustomerOrderNo());
        map.put("inspectionWarehouseCode", order.getInspectionWhCode());
        map.put("inspectionWarehouseName", order.getInspectionWhName());
        map.put("destinationWarehouseCode", order.getDestWhCode());
        map.put("destinationWarehouseName", order.getDestWhName());
        map.put("createdDate", (DateUtil.parse2String(order.getCreated(), DateUtil.FULL_DATE_STRING)));
        map.put("winitProductCode", order.getWinitProductCode());
        map.put("winitProductName", order.getWinitProductName());
        map.put("planShelfCompletedDate", order.getEstimateShelveCompletedDate());
        map.put("logisticsPlanNo", order.getLogisticsPlanId());
        map.put("logisticsPlanName", order.getLogisticsPlanName());
        map.put("importerCode", order.getImporterId());
        map.put("importerName", order.getImporterName());
        map.put("exporterCode", order.getExporterId());
        map.put("exporterName", order.getExporterName());
        map.put("importDeclarationRuleCode", order.getImportDeclarationRuleCode());
        map.put("importDeclarationRuleName", order.getImportDeclarationRuleName());
        map.put("totalPackageQty", order.getOrderPackageQty());
        map.put("totalMerchandiseQty", order.getOrderMerchandiseQty());
        map.put("totalItemQty", order.getOrderItemQty());
        map.put("exportDeclarationType", order.getCustomsDeclarationType());
        map.put("isShowEstimateShelveTime", order.getIsShowEstimateShelveTime());
       
        /************************* 验货提货 ************************/
        if (order.getInboundDispatchinfoVo() == null) {
            order.setInboundDispatchinfoVo(new InboundDispatchinfoVo());
        }
        map.put("inspectionType", order.getInboundDispatchinfoVo().getInspectionType());
        map.put("pickupType", order.getInboundDispatchinfoVo().getPickupType());
        map.put("pickupAddressCode", order.getInboundDispatchinfoVo().getAddressCode());
        map.put("pickupAddress", order.getInboundDispatchinfoVo().getAddress());
        map.put("expressNo", order.getInboundDispatchinfoVo().getExpressNo());
        map.put("expressVendorCode", order.getInboundDispatchinfoVo().getExpressVendorCode());
        map.put("expressVendorName", order.getInboundDispatchinfoVo().getExpressVendorName());
        if (null != order.getInboundDispatchinfoVo().getExpectFromDate() && null !=  order.getInboundDispatchinfoVo().getExpectToDate()) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
            String dateStr = dateFormat.format(order.getInboundDispatchinfoVo().getExpectFromDate());
            String fromTimeStr = timeFormat.format(order.getInboundDispatchinfoVo().getExpectFromDate());
            String toTimeStr = timeFormat.format(order.getInboundDispatchinfoVo().getExpectToDate());
            map.put("reservePickupDate", dateStr);
            map.put("reservePickupTime", fromTimeStr + "-" + toTimeStr);
        }
        //包裹信息
        if(isIncludePackage){
            List<Map<String, Object>> packageList = new ArrayList<Map<String, Object>>();
        	List<InboundPackageVo> pkgList = order.getPkgList();
        	if(CollectionUtils.isNotEmpty(pkgList)){
        	    for (InboundPackageVo inboundPackageVo : pkgList) {
        	        Map<String,Object> packMap=new HashMap<String, Object>();
        	        packMap.put("sellerCaseNo", inboundPackageVo.getCaseNo());
        	        packMap.put("sellerHeight", inboundPackageVo.getSellerHeight());
        	        packMap.put("sellerLength", inboundPackageVo.getSellerLength());
        	        packMap.put("sellerWeight", inboundPackageVo.getSellerWeight());
        	        packMap.put("sellerWidth", inboundPackageVo.getSellerWidth());
        	        packMap.put("packageNo", inboundPackageVo.getPackageSerNo());
        	        packMap.put("height", inboundPackageVo.getHeight());
        	        packMap.put("length", inboundPackageVo.getLength());
        	        packMap.put("weight", inboundPackageVo.getWeight());
        	        packMap.put("width", inboundPackageVo.getWidth());
        	        packageList.add(packMap);
                    
                }
        	}
        	map.put("packageList", packageList);
        }
        //商品信息
        List<InboundMerchandiseDetailsVo> inboundMerList = order.getInboundMerList();
        if(CollectionUtils.isNotEmpty(inboundMerList)){
            List<Map<String, Object>> inboundMerchandiseList = new ArrayList<Map<String, Object>>();
            for (InboundMerchandiseDetailsVo inboundMerchandiseVo : inboundMerList) {
                Map<String,Object> merMap=new HashMap<String, Object>();
                merMap.put("sku", inboundMerchandiseVo.getMerchandiseSerno());
                merMap.put("merchandiseCode", inboundMerchandiseVo.getMerchandiseCode());
                merMap.put("specification", inboundMerchandiseVo.getSpecification());
                merMap.put("quantity", inboundMerchandiseVo.getQuantity());
                inboundMerchandiseList.add(merMap);
            }
            map.put("merchandiseList", inboundMerchandiseList);
        }
        
        return map;
    }


    /** 构建入库单vo信息
     * 
     * @param json
     * @return
     */
    public static InboundOrderVo build(JSONObject json) {
        InboundOrderVo vo = buildInboundOrder(json);
        buildUnpickupInboundOrder(json, vo);
        List<InboundPackageVo> voList = InboundPackageBuilder.buildPackage(json);
        vo.setInboundPackageVos(voList);
        return vo;
    }

    /**
     * 构建物流、提货等信息
     * 
     * @param json
     * @param vo
     */
    private static void buildLogisticInfo(JSONObject json, InboundOrderVo vo) {
        if (InboundEnumConstant.OrderType.STANDARD.getType().equals(vo.getEntryWhType()) 
           || InboundEnumConstant.OrderType.STORAGE_INBOUND.getType().equals(vo.getEntryWhType())) {
            if(json.containsKey("logistics"))
            {
                JSONObject logisticsJson = json.getJSONObject("logistics");
                // 设置物流信息，收货、验货信息
                if (logisticsJson.containsKey("importerCode")) {
                    vo.setImporterId(logisticsJson.getLong("importerCode"));
                }
                if (logisticsJson.containsKey("exporterCode")) {
                    vo.setExporterId(logisticsJson.getLong("exporterCode"));
                }
                if (logisticsJson.containsKey("logisticsPlanNo")) {
                    vo.setLogisticsPlanId(logisticsJson.getLong("logisticsPlanNo"));
                }
                //进口报关规则编码
                if (logisticsJson.containsKey("importDeclarationRuleCode")) {
                    vo.setImportDeclarationRuleCode(logisticsJson.getString("importDeclarationRuleCode"));
                }
                // EOR类型
                if (logisticsJson.containsKey("customsDeclarationType")) {
                    vo.setCustomsDeclarationType(logisticsJson.getString("customsDeclarationType"));
                }
            }
            // 设置物流信息，收货、验货信息
            if (json.containsKey("importerCode")) {
                vo.setImporterId(json.getLong("importerCode"));
            }
            if (json.containsKey("exporterCode")) {
                vo.setExporterId(json.getLong("exporterCode"));
			}
            //进口报关规则编码
            if (json.containsKey("importDeclarationRuleCode")) {
                vo.setImportDeclarationRuleCode(json.getString("importDeclarationRuleCode"));
            }
            // EOR类型
            if (json.containsKey("customsDeclarationType")) {
                vo.setCustomsDeclarationType(json.getString("customsDeclarationType"));
            }
            if (json.containsKey("logisticsPlanNo")) {
                vo.setLogisticsPlanId(json.getLong("logisticsPlanNo"));
            }
            
            JSONObject dispatchInfoJson = json.getJSONObject("dispatchInfo");
            InboundDispatchinfoVo dispatchInfo = InboundPickupBuilder.buildInspectionPickUp(dispatchInfoJson);
            vo.setInboundDispatchinfoVo(dispatchInfo);
        } else if (InboundEnumConstant.OrderType.DIRECT_INNER.getType().equals(vo.getEntryWhType())
                || InboundEnumConstant.OrderType.STORAGE_DIRECT_INNER.getType().equals(vo.getEntryWhType())) {
            if(json.containsKey("isSelfInspection") && json.containsKey("isContainLogisticsSu")){
                if("Y".equals(json.getString("isSelfInspection")) && "Winit".equals(json.getString("isContainLogisticsSu"))){
                    // 设置物流信息，进出口商,文件地址信息
                    if (json.containsKey("logistics")) {
                        JSONObject logisticsJson = json.getJSONObject("logistics");
                        // 设置物流信息，收货、验货信息
                        if (logisticsJson.containsKey("importerCode")) {
                            vo.setImporterId(logisticsJson.getLong("importerCode"));
                        }
                        if (logisticsJson.containsKey("exporterCode")) {
                        	vo.setExporterId(logisticsJson.getLong("exporterCode"));
                        }
                        if (logisticsJson.containsKey("logisticsPlanNo")) {
                            vo.setLogisticsPlanId(logisticsJson.getLong("logisticsPlanNo"));
                        }
                        
                        //进口报关规则编码
                        if (logisticsJson.containsKey("importDeclarationRuleCode")) {
                            vo.setImportDeclarationRuleCode(logisticsJson.getString("importDeclarationRuleCode"));
                        }
                        // EOR类型
                        if (logisticsJson.containsKey("customsDeclarationType")) {
                            vo.setCustomsDeclarationType(logisticsJson.getString("customsDeclarationType"));
                        }
                    }
                    // 构建入参
                    if (json.containsKey("sendPort")) {
                        JSONObject sendPortJson = json.getJSONObject("sendPort");
                        if(sendPortJson.containsKey("sendPortDate")){
                            vo.setSendPortDate(sendPortJson.getDate("sendPortDate"));
                        }else{
                            vo.setSendPortDate(null);
                        }
                        if(sendPortJson.containsKey("containerNo")){
                            vo.setContainerNo(sendPortJson.getString("containerNo"));
                        }else{
                            vo.setContainerNo(null);
                        }
                        if(sendPortJson.containsKey("sendPortType")){
                            vo.setSendPortType(sendPortJson.getString("sendPortType"));
                        }else{
                            vo.setSendPortType(null);
                        }
                        if(sendPortJson.containsKey("pickupCartonAddrCode")){
                            vo.setPickupCartonAddrCode(sendPortJson.getString("pickupCartonAddrCode"));
                        }else{
                            vo.setPickupCartonAddrCode(null);
                        }
                        if(sendPortJson.containsKey("sealNo")){
                            vo.setSealNo(sendPortJson.getString("sealNo"));
                        }else{
                            vo.setSealNo(null);
                        }
                        if(sendPortJson.containsKey("sendPortType")){
                            vo.setSendPortType(sendPortJson.getString("sendPortType"));
                        }else{
                            vo.setSendPortType(null);
                        }
                    }
                }
            }else{
                JSONObject dispatchInfoJson = json.getJSONObject("dispatchInfo");
                InboundDispatchinfoVo dispatchInfo = InboundPickupBuilder.buildInspectionPickUp(dispatchInfoJson);
                vo.setInboundDispatchinfoVo(dispatchInfo);
            }
        } else if (InboundEnumConstant.OrderType.DIRECT_WH.getType().equals(vo.getEntryWhType())) {
            if(json.containsKey("isContainLogisticsSu")){
                if( "Winit".equals(json.getString("isContainLogisticsSu"))){
                    vo.setOnwardVoyageType("Direct");
                    
                    // 设置物流信息，进出口商,文件地址信息
                    if (json.containsKey("logistics")) {
                        JSONObject logisticsJson = json.getJSONObject("logistics");
                        // 设置物流信息，收货、验货信息
                        //新增出口报关类型字段
                        if (logisticsJson.containsKey("importerCode")) {
                            vo.setImporterId(logisticsJson.getLong("importerCode"));
                        }
                        if (logisticsJson.containsKey("exporterCode")) {
                        	vo.setExporterId(logisticsJson.getLong("exporterCode"));
                        }
                        if (logisticsJson.containsKey("logisticsPlanNo")) {
                            vo.setLogisticsPlanId(logisticsJson.getLong("logisticsPlanNo"));
                        }
                        //进口报关规则编码
                        if (logisticsJson.containsKey("importDeclarationRuleCode")) {
                            vo.setImportDeclarationRuleCode(logisticsJson.getString("importDeclarationRuleCode"));
                        }
                        // EOR类型
                        if (logisticsJson.containsKey("customsDeclarationType")) {
                            vo.setCustomsDeclarationType(logisticsJson.getString("customsDeclarationType"));
                        }
                    }
                    // 构建入参
                    if (json.containsKey("sendPort")) {
                        JSONObject sendPortJson = json.getJSONObject("sendPort");
                        if(sendPortJson.containsKey("sendPortDate")){
                            vo.setSendPortDate(sendPortJson.getDate("sendPortDate"));
                        }else{
                            vo.setSendPortDate(null);
                        }
                        if(sendPortJson.containsKey("containerNo")){
                            vo.setContainerNo(sendPortJson.getString("containerNo"));
                        }else{
                            vo.setContainerNo(null);
                        }
                        if(sendPortJson.containsKey("sendPortType")){
                            vo.setSendPortType(sendPortJson.getString("sendPortType"));
                        }else{
                            vo.setSendPortType(null);
                        }
                        if(sendPortJson.containsKey("pickupCartonAddrCode")){
                            vo.setPickupCartonAddrCode(sendPortJson.getString("pickupCartonAddrCode"));
                        }else{
                            vo.setPickupCartonAddrCode(null);
                        }
                        if(sendPortJson.containsKey("sealNo")){
                            vo.setSealNo(sendPortJson.getString("sealNo"));
                        }else{
                            vo.setSealNo(null);
                        }
                        if(sendPortJson.containsKey("sendPortType")){
                            vo.setSendPortType(sendPortJson.getString("sendPortType"));
                        }else{
                            vo.setSendPortType(null);
                        }
                    }
                }
            }
        } else if (InboundEnumConstant.OrderType.LOCATION_INBOUND.getType().equals(vo.getEntryWhType())) {
            JSONObject dispatchInfoJson = json.getJSONObject("dispatchInfo");
            InboundDispatchinfoVo dispatchInfo = InboundPickupBuilder.buildInspectionPickUp(dispatchInfoJson);
            vo.setInboundDispatchinfoVo(dispatchInfo);
        } else {
            throw new ApiException("订单类型不支持！");
        }

        if (json.containsKey("orderNo")) {
            vo.setOrderNo(json.getString("orderNo").trim());
        }
        if (json.containsKey("desc")) {
            vo.setDesc(json.getString("desc").trim());
        }
        if (json.containsKey("customerOrderNo")) {
            vo.setCustomerOrderNo(json.getString("customerOrderNo").trim());
        }
    }

    private static void buildDateAndTime(Map<String, Object> map, Date expectFromDate, Date expectToDate) {
        if (null == expectFromDate || null == expectToDate) {
            // TODO 如果值为空，则写死数据给前端联调先
            expectFromDate = new Date();
            expectToDate = new Date(System.currentTimeMillis() + 10000);
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
        String dateStr = dateFormat.format(expectFromDate);
        String fromTimeStr = timeFormat.format(expectFromDate);
        String toTimeStr = timeFormat.format(expectToDate);

        map.put("pickExpectDate", dateStr);
        map.put("timeFromTo", fromTimeStr + "-" + toTimeStr);
        // System.out.println(map.get("date") + "\r" + map.get("timeFromTo"));
    }

    private static void buildCommon(InboundOrderVo vo, JSONObject json) {
        if ("logistics".equals(json.getString("unitName"))) {
        	//新增出口报关类型字段
        	if(json.containsKey("exportDeclarationType")){
        		 vo.setCustomsDeclarationType(json.getString("exportDeclarationType"));
        	}
        	if (json.containsKey("exporterCode")) {
        		vo.setExporterId(json.getLong("exporterCode"));
        	}
            if (json.containsKey("importerCode")) {
                vo.setImporterId(json.getLong("importerCode"));
            }
            if (json.containsKey("logisticsPlanNo")) {
                vo.setLogisticsPlanId(json.getLong("logisticsPlanNo"));
            }
            if (json.containsKey("customsData")) {
                vo.setCustomsData(json.getString("customsData"));
            }
            //进口报关规则编码
            if (json.containsKey("importDeclarationRuleCode")) {
                vo.setImportDeclarationRuleCode(json.getString("importDeclarationRuleCode"));
            }
            // EOR类型
            if (json.containsKey("customsDeclarationType")) {
                vo.setCustomsDeclarationType(json.getString("customsDeclarationType"));
            }
        } else {
            if (json.containsKey("warehouseCode")) {
                vo.setInspectionWhCode(json.getString("warehouseCode").trim());
            } else {
                if (json.containsKey("destinationWarehouseCode")) {
                    vo.setInspectionWhCode(json.getString("destinationWarehouseCode").trim());
                }
            }

            if (json.containsKey("destinationWarehouseCode")) {
                vo.setDestWhCode(json.getString("destinationWarehouseCode").trim());
            }

            if (json.containsKey("productCode")) {
                vo.setWinitProductCode(json.getString("productCode").trim());
            }

            if (json.containsKey("customerOrderNo")) {
                vo.setCustomerOrderNo(json.getString("customerOrderNo").trim());
            }
        }

        if (json.containsKey("orderNo")) {
            vo.setOrderNo(json.getString("orderNo").trim());
        }

        if (json.containsKey("orderType")) {
            vo.setEntryWhType(json.getString("orderType").trim());
        }
        if (json.containsKey("unitName")) {
            vo.setUnitName(json.getString("unitName").trim());
        }
    }

    /**
     * 构建订单轨迹
     * 
     * @return
     */
    public static List<Map<String, Object>> buildInboundOrderTrackingList(List<InboundOrderTrackingVo> tList) {
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        for (InboundOrderTrackingVo vo : tList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("date", vo.getTrackingDate());
            map.put("trackingDesc", vo.getTrackingDesc());
            map.put("location", vo.getTrackingLocation());
            map.put("trackingCode", vo.getTrackingCode());
            mapList.add(map);
        }

        return mapList;

    }

    public static void main(String[] args) {
        buildDateAndTime(new HashMap<String, Object>(), null, null);
    }
}
